package org.jeecg.modules.shangt.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.shangt.entity.ShangtGroup;
import org.jeecg.modules.shangt.entity.ShangtRtn;
import org.jeecg.modules.shangt.entity.ShangtUser;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.SSLException;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ShangTApiHelper {
    //输入你的app_key
    String app_key = "95268aaba2274824";
//    String app_key = "be48f3f1309c6deb";
    //输入你的app_secret
    String app_secret = "f8744b3b320df86a50c314c3340c9449";
//    String app_secret = "533ebb786f842af860f0bb16e0a2c787";
    String baseUrl = "http://10.2.102.163";
//    String baseUrl = "https://link.bi.sensetime.com";
    String BOUNDARY = "----WebKitFormBoundarygrBcuHVTeNQcBtqn";
    String name;

    public String picturePrefix = "http://10.2.102.163/v1/image/1/";
//    public String picturePrefix = "https://link.bi.sensetime.com/v1/image/1/";

    @Autowired
    RestTemplate restTemplate;

    Long getTimestamp() {
        return System.currentTimeMillis();
    }

    String getSign(String timestamp) {
        String code = timestamp + "#" + app_secret;
        return getMD5(code);
    }

    String getMD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }
        return result;
    }

    byte[] doPost(String strUrl, Map<String, Object> params, Map<String, byte[]> fileParams) throws Exception {
        URL url = new URL(strUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json, text/plain, */*"); // 设置接收数据的格式
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 设置发送数据的格式
        connection.setRequestProperty("Charset", "UTF-8");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        Iterator it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry) it.next();
            String key = entry.getKey();
            Object value = entry.getValue();

            out.writeBytes("--" + BOUNDARY + "\r\n");
            out.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"");
            out.writeBytes("\r\n\r\n");
            out.writeBytes(value + "\r\n");
        }
        if (fileParams != null && fileParams.size() > 0) {
            Iterator fileIt = fileParams.entrySet().iterator();
            while (fileIt.hasNext()) {
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIt.next();
                out.writeBytes("--" + BOUNDARY + "\r\n");
                out.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + name + "\"");
                out.writeBytes("\r\n");
                out.writeBytes("Content-Type: image/jpeg");//此处很关键
                out.writeBytes("\r\n\r\n");
                out.write(fileEntry.getValue());
                out.writeBytes("\r\n");
            }
        }
        out.writeBytes("--" + BOUNDARY + "--");
        out.flush();
        out.close();
        InputStream in = null;
        int code = connection.getResponseCode();
        try {
            if (code == 200) {
                in = connection.getInputStream();
            } else {
                in = connection.getErrorStream();
            }
        } catch (SSLException e) {
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baout = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len;
        while ((len = in.read(buff)) != -1) {
            baout.write(buff, 0, len);
        }
        byte[] bytes = baout.toByteArray();
        in.close();
        return bytes;
    }

    byte[] getBytes(File f) {
        try {
            InputStream in = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = in.read(b)) != -1)
                out.write(b, 0, n);
            in.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            System.out.println("***请设置文件路径***");
        }
        return null;
    }

    public List<ShangtUser> getEmployeeList(String type) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));
        params.put("type", type);

        ShangtRtn obj = restTemplate.getForObject(baseUrl + "/api/v1/user/list?app_key={app_key}&timestamp={timestamp}&sign={sign}&type={type}", ShangtRtn.class, params);
        return JSON.parseObject(JSON.toJSONString(obj.getData()), new TypeReference<List<ShangtUser>>(){});
    }

    public List<ShangtGroup> getEmployeeGroupList(String type) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));
        params.put("page", 1);
        params.put("size", 999);
        params.put("type", type);

        ShangtRtn obj = restTemplate.getForObject(baseUrl + "/api/v1/group?app_key={app_key}&timestamp={timestamp}&sign={sign}&page={page}&size={size}&type={type}", ShangtRtn.class, params);

        if(obj.getData() != null) {
            Map map = (Map)obj.getData();
            List<ShangtGroup> list = JSON.parseObject(JSON.toJSONString(map.get("data")), new TypeReference<List<ShangtGroup>>(){});
            return list;
        }

        return null;
    }

    public ShangtRtn createEmployee(ShangtUser shangtUser, String touxPath) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        try {
            shangtUser.setName(new String(shangtUser.getName().getBytes("UTF-8"), "iso8859-1"));
        } catch (Exception error) {
            ;
        }

        params = BeanUtil.beanToMap(shangtUser);
        params.remove("id");
        params.remove("type");
        params.remove("groupList");

        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));

        System.out.println(JSON.toJSONString(params));

        if(touxPath != null && touxPath.length() > 0) {
            File avatar_file = new File(touxPath);
            name = avatar_file.getName();
            fileParams.put("avatarFile", getBytes(avatar_file));
        }

        byte[] rtn = null;
        try {
            rtn = doPost(baseUrl + "/api/v1/user", params, fileParams);
            String result = new String(rtn);
            System.out.println(result);
            ShangtRtn shangtRtn = JSON.parseObject(result, new TypeReference<ShangtRtn>(){});
            return shangtRtn;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public ShangtRtn editEmployee(ShangtUser shangtUser, String touxPath) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        try {
            shangtUser.setName(new String(shangtUser.getName().getBytes("UTF-8"), "iso8859-1"));
        } catch (Exception error) {
            ;
        }

        params = BeanUtil.beanToMap(shangtUser);
        params.remove("type");
        params.remove("groupList");

        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));

        System.out.println(JSON.toJSONString(params));

        if(touxPath != null && touxPath.length() > 0) {
            File avatar_file = new File(touxPath);
            name = avatar_file.getName();
            fileParams.put("avatarFile", getBytes(avatar_file));
        }

        byte[] rtn = null;
        try {
            rtn = doPost(baseUrl + "/api/v2/user/update/" + shangtUser.getId(), params, fileParams);
            String result = new String(rtn);
            System.out.println(result);
            ShangtRtn shangtRtn = JSON.parseObject(result, new TypeReference<ShangtRtn>(){});
            return shangtRtn;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public ShangtRtn deleteUser(String id) {
        Map<String, Object> params = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));
        params.put("id", id);

        return restTemplate.getForObject(baseUrl + "/api/v1/user/delete/{id}?app_key={app_key}&timestamp={timestamp}&sign={sign}", ShangtRtn.class, params);

    }

    public ShangtRtn createVisitor(ShangtUser shangtUser, String touxPath) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        try {
            shangtUser.setName(new String(shangtUser.getName().getBytes("UTF-8"), "iso8859-1"));
            shangtUser.setGuestPurpose(new String(shangtUser.getGuestPurpose().getBytes("UTF-8"), "iso8859-1"));
        } catch (Exception error) {
            ;
        }

        params = BeanUtil.beanToMap(shangtUser);
        params.remove("id");
        params.remove("type");
        params.remove("gender");

        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));

        System.out.println(JSON.toJSONString(params));

        if(touxPath != null && touxPath.length() > 0) {
            File avatar_file = new File(touxPath);
            name = avatar_file.getName();
            fileParams.put("avatarFile", getBytes(avatar_file));
        }

        byte[] rtn = null;
        try {
            rtn = doPost(baseUrl + "/api/v1/guest", params, fileParams);
            String result = new String(rtn);
            System.out.println(result);
            ShangtRtn shangtRtn = JSON.parseObject(result, new TypeReference<ShangtRtn>(){});
            return shangtRtn;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public ShangtRtn editVisitor(ShangtUser shangtUser, String touxPath) {
        //表单文本参数
        Map<String, Object> params = new HashMap();

        try {
            shangtUser.setName(new String(shangtUser.getName().getBytes("UTF-8"), "iso8859-1"));
            shangtUser.setGuestPurpose(new String(shangtUser.getGuestPurpose().getBytes("UTF-8"), "iso8859-1"));
        } catch (Exception error) {
            ;
        }

        params = BeanUtil.beanToMap(shangtUser);
        params.remove("type");
        params.remove("groupList");

        //表单文件参数
        Map<String, byte[]> fileParams = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));

        System.out.println(JSON.toJSONString(params));

        if(touxPath != null && touxPath.length() > 0) {
            File avatar_file = new File(touxPath);
            name = avatar_file.getName();
            fileParams.put("avatarFile", getBytes(avatar_file));
        }

        byte[] rtn = null;
        try {
            rtn = doPost(baseUrl + "/api/v1/guest/update/" + shangtUser.getId(), params, fileParams);
            String result = new String(rtn);
            System.out.println(result);
            ShangtRtn shangtRtn = JSON.parseObject(result, new TypeReference<ShangtRtn>(){});
            return shangtRtn;

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public ShangtRtn deleteVisitor(String id) {
        Map<String, Object> params = new HashMap();

        Long timestamp = getTimestamp();
        params.put("app_key", app_key);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", getSign(String.valueOf(timestamp)));
        params.put("id", id);

        return restTemplate.getForObject(baseUrl + "/api/v1/guest/delete/{id}?app_key={app_key}&timestamp={timestamp}&sign={sign}", ShangtRtn.class, params);
    }
}
